﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;

public class ResLoader : MonoBehaviour
{

#if UNITY_STANDALONE_WIN || UNITY_EDITOR  
	public static readonly string prefix = "file:///";  
#elif UNITY_ANDROID  
	public static readonly string prefix = "jar:file://";
#elif UNITY_IPHONE  
	public static readonly string prefix = "";  

#else
	public static readonly string prefix = ""
#endif  


	public static bool IsHttpUrl(string url)
	{
		if (url.StartsWith ("http://") || url.StartsWith ("https://") || url.StartsWith ("ftp://"))
			return true;

		return false;
	}

	// 网络文件对应本地目录
	public static string Url2LocalPath( string httpUrl )
	{
		int idx = httpUrl.IndexOf ('/', 8);
		string res = httpUrl.Substring (idx);
		string path = Application.persistentDataPath + res;
		return path;
	}

	// 是否已经下载过了
	// ex : https://www.dope.ren/feizhougu/001/01_part1.mp4
	public static bool HaveDownload( string path )
	{
        if (string.IsNullOrEmpty(path))
            return true;

		// 本地文件
		if (IsHttpUrl (path) == false) {
			return true;
		}

		string file = Url2LocalPath (path);

		if (File.Exists (file))
			return true;
		else
			return false;

	}

    // 清除已经下载的url
    public static void DelDownload( string path )
    {
        string res = "";

        // 本地文件
        if (IsHttpUrl(path) == false)
            res = path;
        else
            res = Url2LocalPath(path);

        if (File.Exists(res))
        {
            File.Delete(res);
        }

    }

	class DLData
	{
		public string url = "";
		public Action<float> progressCallback = null;
		public Action<WWW> finishCallback = null;
		public string savePath = "";

		public DLData(string Url, Action<float> ProgressCallback, Action<WWW> FinishCallback, string SavePath)
		{
			url = Url;
			progressCallback = ProgressCallback;
			finishCallback = FinishCallback;
			savePath = SavePath;
		}
	}
	private static List<DLData> urls = new List<DLData> ();


	void Update()
	{
		if (!isBusy && urls.Count > 0) {
		
			DLData d = urls [0];
			urls.RemoveAt (0);

			StartCoroutine (BeginLoad(d));
		}
	}

	public static void Load( string url, Action<float> ProgressCallback, Action<WWW> FinishCallback, bool AutoSaveHttpRes, bool FindLocal = true )
	{
		if (FindLocal) {
			if (HaveDownload (url)) {
				if (IsHttpUrl (url))
					Load ( "file://" + Url2LocalPath (url), ProgressCallback, FinishCallback, null);
				else
					Load (url, ProgressCallback, FinishCallback, null);

				return;
			}

		}
		
		if (AutoSaveHttpRes && IsHttpUrl (url))
			Load (url, ProgressCallback, FinishCallback, Url2LocalPath (url));
		else
			Load (url, ProgressCallback, FinishCallback, null);
	}

	// 下载接口
	public static void Load( string url, Action<float> ProgressCallback, Action<WWW> FinishCallback, string savePath)
	{
        Resources.UnloadUnusedAssets();

		DLData d = new DLData (url, ProgressCallback, FinishCallback, savePath);

		urls.Add (d);

	}


	private static bool isBusy = false;
	// 下载资源
	IEnumerator BeginLoad( DLData data )
	{
		isBusy = true;

		Debug.Log ("data.url = " + data.url + "     ........................");
		WWW www = new WWW(data.url);

		while (!www.isDone) {
		
			if ( data.progressCallback != null)
				data.progressCallback (www.progress);

			yield return new WaitForEndOfFrame ();

		}

		yield return www;


	if (!string.IsNullOrEmpty( www.error) ) {
			Debug.Log ("加载错误  " + www.error);
			if (data.finishCallback != null)
				data.finishCallback (www);
		}
		else {

			if ( !string.IsNullOrEmpty( data.savePath ) )
            {
                WriteToFile(data.savePath, www.bytes);
                Debug.Log("写入了文件:" + data.savePath + "      内容:" + www.bytes);
            }


			if (data.finishCallback != null)
				data.finishCallback ( www );

		}

		isBusy = false;
	}

	public static bool WriteToFile( string path, byte[] bytes)
	{
		string dir = path.Substring (0, path.LastIndexOf ('/'));

		if (Directory.Exists (dir) == false)
			Directory.CreateDirectory (dir);

		File.WriteAllBytes (path, bytes);

		return true;
	}
		

    public static void PlayAudio( AudioSource audio, string url )
    {
        if (audio == null || string.IsNullOrEmpty(url))
            return;

        ResLoader.Load(url, null, (www) => {

            AudioClip audioClip = WWWAudioExtensions.GetAudioClip(www);
            audio.clip = audioClip;

            audio.Play();
        }, true, true);
    }





}


